package com.yangyu.bare.controller;

import com.yangyu.bare.annotation.ApiLog;
import com.yangyu.bare.result.BareResult;
import com.yangyu.bare.service.BareService;
import com.yangyu.bare.utils.ResponseUtil;
import com.yangyu.bare.utils.ReturnObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.BufferedInputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 外部接口
 */
@Api(tags = "短视频,图片去水印")
@Controller
public class ApiController {

    @Resource
    private BareService bareService;

    @RequestMapping(method = RequestMethod.GET, path = {"/"})
    public String index() {
        return "index";
    }

    /**
     * 获取无水印资源地址列表
     *
     * @param link 复制的链接
     */
    @ApiLog("视频解析聚合接口")
    @ApiOperation(value = "聚合接口", response = BareResult.class)
    @PostMapping("/parseVideoUrl")
    @ResponseBody
    public ReturnObject<BareResult> bare(
            @NotBlank(message = "请输入复制链接")
            @ApiParam("复制的链接")
            @RequestParam("link") String link) throws Exception {
        return ResponseUtil.ok(bareService.parse(link));
    }

    @GetMapping("/asyncData")
    @ResponseBody
    public void asyncData(String link, String desc) {
        ServletRequestAttributes getServletRequest = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response =  getServletRequest.getResponse();
        try {
            URLDecoder.decode(link, "UTF-8");
            if (StringUtils.isEmpty(link)) {
                throw new RuntimeException("remoteFileUrl is invalid!");
            }
            URL uri = new URL(link);
            BufferedInputStream in = null;
            // 这和上面两句一样的效果
            in = new BufferedInputStream(uri.openStream());
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(desc, "UTF-8") + "\"");
            int i;
            while ((i = in.read()) != -1) {
                response.getOutputStream().write(i);
            }
            in.close();
            response.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}